<template>
  <div class="batch-management">
    <div class="batch-header">
      <h3>批次管理</h3>
      <el-button type="primary" @click="showAddDialog">生成新批次</el-button>
    </div>

    <!-- 批次列表 -->
    <el-table :data="batchList" style="width: 100%" v-loading="loading">
      <el-table-column prop="batch_id" label="批次号" width="180"></el-table-column>
      <el-table-column prop="product_name" label="产品名称" width="180"></el-table-column>
      <el-table-column prop="supplier_name" label="生产商"></el-table-column>
      <el-table-column prop="production_quantity" label="数量">
        <template slot-scope="scope">
          {{ scope.row.production_quantity }} {{ scope.row.unit }}
        </template>
      </el-table-column>
      <el-table-column prop="production_date" label="生产日期" width="120">
        <template slot-scope="scope">
          {{ formatDate(scope.row.production_date) }}
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="viewDetails(scope.row)">查看详情</el-button>
          <el-button size="mini" type="primary" @click="generateQRCode(scope.row)">生成溯源码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 生成新批次对话框 -->
    <el-dialog title="生成新批次" :visible.sync="dialogVisible" width="500px">
      <el-form :model="batchForm" :rules="rules" ref="batchForm" label-width="100px">
        <el-form-item label="产品" prop="product_id">
          <el-select v-model="batchForm.product_id" placeholder="请选择产品">
            <el-option
              v-for="item in products"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存储温度" prop="storage_temp">
          <el-input-number v-model="batchForm.storage_temp" :precision="1" :step="0.5"></el-input-number>
          <span class="unit">°C</span>
        </el-form-item>
        <el-form-item label="生产数量" prop="production_quantity">
          <el-input-number v-model="batchForm.production_quantity" :precision="0" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="batchForm.unit" placeholder="请选择单位">
            <el-option label="件" value="件"></el-option>
            <el-option label="盒" value="盒"></el-option>
            <el-option label="箱" value="箱"></el-option>
            <el-option label="kg" value="kg"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="质检员" prop="quality_inspector">
          <el-input v-model="batchForm.quality_inspector" placeholder="请输入质检员姓名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBatch">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="批次详情" :visible.sync="detailVisible" width="700px">
      <div v-if="batchDetail" class="batch-detail">
        <el-tabs>
          <el-tab-pane label="基本信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="批次号">{{ batchDetail.batch_number }}</el-descriptions-item>
              <el-descriptions-item label="产品名称">{{ batchDetail.product_name }}</el-descriptions-item>
              <el-descriptions-item label="生产商">{{ batchDetail.supplier_name }}</el-descriptions-item>
              <el-descriptions-item label="产品代码">{{ batchDetail.product_code }}</el-descriptions-item>
              <el-descriptions-item label="产品类别">{{ batchDetail.category }}</el-descriptions-item>
              <el-descriptions-item label="生产日期">{{ formatDate(batchDetail.production_date) }}</el-descriptions-item>
              <el-descriptions-item label="保质期">{{ batchDetail.shelf_life }} 天</el-descriptions-item>
              <el-descriptions-item label="存储条件">{{ batchDetail.storage_conditions }}</el-descriptions-item>
              <el-descriptions-item label="生产数量">{{ batchDetail.production_quantity }} {{ batchDetail.unit }}</el-descriptions-item>
              <el-descriptions-item label="质检员">{{ batchDetail.quality_inspector }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="区块链信息" v-if="batchDetail.blockchain_data">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="数据哈希">{{ batchDetail.blockchain_data.data_hash }}</el-descriptions-item>
              <el-descriptions-item label="区块哈希">{{ batchDetail.blockchain_data.block_hash }}</el-descriptions-item>
              <el-descriptions-item label="前序哈希">{{ batchDetail.blockchain_data.prev_hash }}</el-descriptions-item>
              <el-descriptions-item label="存证时间">{{ formatDateTime(batchDetail.blockchain_data.created_at) }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 溯源码对话框 -->
    <el-dialog title="溯源二维码" :visible.sync="qrcodeVisible" width="400px">
      <div v-if="qrcodeData" class="qrcode-container">
        <div class="qrcode-info">
          <p><strong>批次号：</strong>{{ qrcodeData.batch_number }}</p>
          <p><strong>产品名称：</strong>{{ qrcodeData.product_name }}</p>
          <p><strong>生产商：</strong>{{ qrcodeData.supplier_name }}</p>
        </div>
        <div class="qrcode-image">
          <img :src="'data:image/png;base64,' + qrcodeData.qrcode_base64" alt="溯源二维码" />
        </div>
        <div class="qrcode-tips">
          <p>请将此二维码印制在产品包装上</p>
          <p>消费者可通过扫描此码查看产品全部溯源信息</p>
        </div>
        <div class="qrcode-actions">
          <el-button type="primary" @click="downloadQRCode">下载二维码</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'BatchManagement',
  data() {
    return {
      loading: false,
      batchList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      detailVisible: false,
      qrcodeVisible: false,
      products: [],
      batchForm: {
        product_id: '',
        storage_temp: 4.0,
        production_quantity: 100,
        unit: '件',
        quality_inspector: ''
      },
      rules: {
        product_id: [
          { required: true, message: '请选择产品', trigger: 'change' }
        ],
        storage_temp: [
          { required: true, message: '请输入存储温度', trigger: 'blur' }
        ],
        production_quantity: [
          { required: true, message: '请输入生产数量', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ]
      },
      batchDetail: null,
      qrcodeData: null
    }
  },
  created() {
    this.fetchBatchList()
    this.fetchProducts()
  },
  methods: {
    async fetchBatchList() {
      this.loading = true
      try {
        const response = await axios.get('/api/batches', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize
          }
        })
        this.batchList = response.data.items
        this.total = response.data.total
      } catch (error) {
        this.$message.error('获取批次列表失败')
        console.error('获取批次列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    async fetchProducts() {
      try {
        const response = await axios.get('/api/products')
        // Correctly assign the items array from the response
        if (response.data && response.data.items) {
          this.products = response.data.items
        } else {
          // Handle cases where the structure might be different or data is missing
          this.products = response.data || [] 
          console.warn('Product data structure might be unexpected:', response.data)
        }
      } catch (error) {
        this.$message.error('获取产品列表失败')
        console.error('获取产品列表失败:', error)
      }
    },
    showAddDialog() {
      this.dialogVisible = true
      this.batchForm = {
        product_id: '',
        storage_temp: 4.0,
        production_quantity: 100,
        unit: '件',
        quality_inspector: ''
      }
    },
    async submitBatch() {
      try {
        await this.$refs.batchForm.validate()
        this.loading = true
        await axios.post('/api/batches', this.batchForm)
        
        this.$message.success('批次创建成功')
        this.dialogVisible = false
        this.fetchBatchList()
      } catch (error) {
        this.$message.error('批次创建失败: ' + ((error.response && error.response.data && error.response.data.error) || error.message))
        console.error('批次创建失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchBatchList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchBatchList()
    },
    async viewDetails(row) {
      try {
        const response = await axios.get(`/api/batches/${row.id}`)
        this.batchDetail = response.data
        this.detailVisible = true
      } catch (error) {
        this.$message.error('获取批次详情失败')
        console.error('获取批次详情失败:', error)
      }
    },
    async generateQRCode(row) {
      try {
        const response = await axios.get(`/api/batches/${row.id}/qrcode`)
        this.qrcodeData = response.data
        this.qrcodeVisible = true
      } catch (error) {
        this.$message.error('生成溯源码失败')
        console.error('生成溯源码失败:', error)
      }
    },
    downloadQRCode() {
      if (!this.qrcodeData) return
      
      const link = document.createElement('a')
      link.href = 'data:image/png;base64,' + this.qrcodeData.qrcode_base64
      link.download = `溯源码_${this.qrcodeData.batch_number}.png`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      const date = new Date(dateStr)
      return date.toISOString().split('T')[0]
    },
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return '-'
      const date = new Date(dateTimeStr)
      return date.toLocaleString()
    }
  }
}
</script>

<style scoped>
.batch-management {
  padding: 20px;
}
.batch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.batch-header h3 {
  margin: 0;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.unit {
  margin-left: 10px;
  color: #606266;
}
.batch-detail {
  padding: 10px;
}
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}
.qrcode-info {
  margin-bottom: 15px;
  width: 100%;
}
.qrcode-image {
  margin-bottom: 15px;
}
.qrcode-image img {
  max-width: 200px;
}
.qrcode-tips {
  margin-bottom: 15px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
.qrcode-actions {
  margin-top: 15px;
}
</style> 